package com.sxm.yiwei.activitis;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.R;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.tools.REXTools;
import com.sxm.yiwei.utils.InternetAddressUtis;
import com.sxm.yiwei.views.ValidationCode;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

public class MsgNewPhoneActivity extends BaseActivity implements View.OnClickListener{

    private ImageView carback;
    private LinearLayout carsearch;
    private SharedPreferences sharedPreferences;
    private String appId;
    private String userId;
    private String token;
    private String messageId;
    private Button newphonesurebt;
    private Button getCode;
    private EditText inPhone;
    private EditText inCode;
    private EditText inImgCode;
    private String phone;
    private String code;
    private String imgCode;
    private ValidationCode picCode;
    private ImageView backmain;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fw_car);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid", "0");
        userId = sharedPreferences.getString("userId", "1");
        token = sharedPreferences.getString("token", "2");
        initCarView();
    }

    private void initCarView() {
        backmain = (ImageView) findViewById(R.id.msgnewphone_backmain);
        carback = (ImageView) findViewById(R.id.msgnewphone_back);
        newphonesurebt = (Button) findViewById(R.id.msgnewphone_surebt);
        getCode = (Button) findViewById(R.id.msgnewphone_getcode);
        inPhone = (EditText) findViewById(R.id.msgnewphone_inphone);
        inCode = (EditText) findViewById(R.id.msgnewphone_incode);
        inImgCode = (EditText) findViewById(R.id.msgnewphone_inimgcode);
        picCode = (ValidationCode) findViewById(R.id.msgnewphone_imgcode);

        carback.setOnClickListener(this);
        getCode.setOnClickListener(this);
        backmain.setOnClickListener(this);
        newphonesurebt.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        getInPutData();
        switch (v.getId()){

            case R.id.msgnewphone_back:
                finish();
                break;
            case R.id.msgnewphone_surebt:
                if (imgCode.equals("")){
                    Toast.makeText(this, "请输入图形验证码", Toast.LENGTH_SHORT).show();
                }else {
                    if (phone.equals("")){
                        Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
                    }else {

                        if (imgCode.equals(picCode.getCodeString())){

                            if (code.equals("")){
                                Toast.makeText(this, "请输入短信验证码", Toast.LENGTH_SHORT).show();
                            }else {
                                reviseNewPhone();
                            }
                        }else {
                            Toast.makeText(this, "图形验证码不正确，请注意大小写", Toast.LENGTH_SHORT).show();
                        }
                    }
                }

                break;
            case R.id.msgnewphone_getcode:
                if (imgCode.equals("")){
                    Toast.makeText(this, "请输入图形验证码", Toast.LENGTH_SHORT).show();
                }else {
                    if (phone.equals("")&& !REXTools.isPhoneNumber(phone)){
                        Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
                    }else {

                        if (imgCode.equals(picCode.getCodeString())){
                            MyTimer myTimer = new MyTimer(120000,1000);
                            myTimer.start();
                            getCode();
                        }else {
                            Toast.makeText(this, "图形验证码不正确，请注意大小写", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
                break;
        }
    }
        // 修改手机号码
    private void reviseNewPhone() {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.UPDATAPHONE);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token", token);
        params.addHeader("appId", appId);
        params.addHeader("userId", userId);
        JSONObject object = new JSONObject();
        object.put("mobile",phone);
        object.put("messageId",messageId);
        object.put("code",code);
        params.setBodyContent(object.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                JSONObject obj = JSON.parseObject(result);
                String status = obj.getString("status");
                if (status.equals("1")){
                    Intent intent = new Intent(MsgNewPhoneActivity.this,MsgRevisePhoneFinishActivity.class);
                    intent.putExtra("phone",phone);
                    startActivity(intent);
                }else {
                    String failure = obj.getString("failure");
                    if (failure.equals("1001")){
                        Toast.makeText(MsgNewPhoneActivity.this, "该手机号码已注册", Toast.LENGTH_SHORT).show();
                    }else if (failure.equals("1003")){
                        Toast.makeText(MsgNewPhoneActivity.this, "该手机号码已被禁用", Toast.LENGTH_SHORT).show();
                    }else if (failure.equals("1005")){
                        Toast.makeText(MsgNewPhoneActivity.this, "短信验证码错误，请重新获取", Toast.LENGTH_SHORT).show();
                    }else {}
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    // 获取输入内容
    private void getInPutData() {
        phone = String.valueOf(inPhone.getText());
        code = String.valueOf(inCode.getText());
        imgCode = String.valueOf(inImgCode.getText());

    }


    // 获取验证码
    public void getCode() {

        RequestParams params = new RequestParams(InternetAddressUtis.Url+"/verify/sendCode");
        params.addHeader("Content-Type","application/json");
        params.addHeader("token", token);
        params.addHeader("appId", appId);
        params.addHeader("userId", userId);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type","5");
        params.addParameter("params",jsonObject.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d("tag", "onSuccess: 验证码-"+result);
                com.alibaba.fastjson.JSONObject obj = JSON.parseObject(result);
                // 获取messageid
                String status = obj.getString("status");
                if (status.equals("1")){
                    String data = obj.getString("data");
                    JSONObject object = JSON.parseObject(data);
                    messageId = object.getString("messageId");

                }else {}


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("tag", "onError: 演这个吗--"+ex);
                ErrType.errType(MsgNewPhoneActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    class MyTimer extends CountDownTimer {
        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                  倒计时数        to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *           倒计时间隔               {@link #onTick(long)} callbacks.
         */
        public MyTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            getCode.setClickable(false);
            getCode.setText(millisUntilFinished/1000+" s 后发送");
        }

        @Override
        public void onFinish() {
            getCode.setClickable(true);
            getCode.setText("验证码");
        }
    }
}
